package net.sudot.chess.business.controller.web;

import net.sudot.chess.business.controller.AbstractBaseController;
import net.sudot.chess.business.model.Customer;
import net.sudot.chess.business.model.VerifyCodeHistory;
import net.sudot.chess.business.service.CustomerService;
import net.sudot.chess.business.service.VerifyCodeHistoryService;
import net.sudot.chess.constant.SessionConstants;
import net.sudot.chess.util.ObjectUtil;
import net.sudot.chess.util.SMSUtil;
import net.sudot.commons.security.LoginUser;
import net.sudot.commons.utils.Pbkdf2PasswordEncoder;
import net.sudot.commons.utils.ResponseMessage;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * 客户控制器
 *
 * @author tangjialin on 2018-02-03.
 */
//此功能暂时不使用 at:2018年08月19日
//@Controller
@RequestMapping(value = "/customer/mobile")
public class CustomerMobileController extends AbstractBaseController {

    @Resource
    private CustomerService customerService;
    @Resource
    private VerifyCodeHistoryService verifyCodeHistoryService;

    /**
     * 绑定手机号码
     *
     * @return 返回号码绑定视图
     */
    @GetMapping("/bind")
    public String bind() {
        return "customer/mobile-bind";
    }

    /**
     * 发送验证码
     *
     * @param mobile  手机号码
     * @param request HttpServletRequest
     * @return 返回发送结果
     */
    @PostMapping("/sendAuthCode")
    @ResponseBody
    public ResponseMessage sendAuthCode(String mobile, HttpServletRequest request) {
        ResponseMessage responseMessage = new ResponseMessage(false);
        if (!ObjectUtil.isMobile(mobile)) {
            return responseMessage.setMessage("请输入正确的手机号码");
        }
        Customer existCustomer = customerService.findByMobile(mobile);
        if (existCustomer != null) { return responseMessage.setMessage("此号码已被使用,请更换其他手机号码"); }
        HttpSession session = request.getSession();
        Long verifyCodeSendTime = (Long) session.getAttribute(SessionConstants.VERIFY_CODE_SEND_TIME);
        long currentTimeMillis = System.currentTimeMillis();
        if (verifyCodeSendTime != null && verifyCodeSendTime + 1000L * 60 > currentTimeMillis) {
            return responseMessage.setMessage("您的操作太快了,请稍做休息");
        }
        String randomChar = SMSUtil.getRandomCode(6);
        session.setAttribute(SessionConstants.VERIFY_CODE, randomChar);
        session.setAttribute(SessionConstants.VERIFY_CODE_SEND_TIME, System.currentTimeMillis());

        VerifyCodeHistory verifyCodeHistory = new VerifyCodeHistory();
        verifyCodeHistory.setMobile(mobile).setCode(randomChar);
        verifyCodeHistoryService.save(verifyCodeHistory);
        return responseMessage.setSuccess(true);
    }

    /**
     * 绑定手机号码及设置密码
     *
     * @param customer 登录用户信息
     * @param mobile   绑定的手机号码
     * @param authCode 手机验证码
     * @param password 设置的新密码
     * @param request  HttpServletRequest
     * @return 返回绑定结果
     */
    @PostMapping("/bind")
    @ResponseBody
    public ResponseMessage bind(@LoginUser Customer customer, String mobile, String authCode, String password, HttpServletRequest request) {
        ResponseMessage responseMessage = new ResponseMessage();
        if (!ObjectUtil.isMobile(mobile)) {
            return responseMessage.setMessage("请输入正确的手机号码");
        }
        if (!ObjectUtil.isEmpty(customer.getMobile())) {
            return responseMessage.setMessage("已绑定手机号码,无需重复绑定");
        }
        if (ObjectUtil.isEmpty(authCode)) { return responseMessage.setMessage("请输入取验证码"); }
        int len = password == null ? 0 : password.length();
        if (len == 0) { return responseMessage.setMessage("请设置密码"); }
        if (len < 6 || len > 18) { return responseMessage.setMessage("密码需6-18位"); }
        Customer existCustomer = customerService.findByMobile(mobile);
        if (existCustomer != null) { return responseMessage.setMessage("此号码已被绑定,请更换其他手机号码"); }
        HttpSession session = request.getSession();
        String sessionVerifyCode = (String) session.getAttribute(SessionConstants.VERIFY_CODE);
        Long verifyCodeSendTime = (Long) session.getAttribute(SessionConstants.VERIFY_CODE_SEND_TIME);
        if (verifyCodeSendTime == null) { return responseMessage.setMessage("请先获取验证码"); }
        long currentTimeMillis = System.currentTimeMillis();
        // 失效时间:10分钟
        if (verifyCodeSendTime + 1000L * 60 * 10 < currentTimeMillis) {
            return responseMessage.setMessage("验证码失效，请重新获取验证码");
        }
        if (authCode == null || authCode.isEmpty() || !authCode.equals(sessionVerifyCode)) {
            return responseMessage.setMessage("验证码填写错误，请输入正确的验证码");
        }
        customer.setUsername(mobile);
        customer.setMobile(mobile);
        customer.setPassword(Pbkdf2PasswordEncoder.createHash(password));
        customerService.update(customer);
        return responseMessage.setSuccess(true);
    }

    /**
     * 更换手机号码
     *
     * @return 返回号码绑定视图
     */
    @GetMapping("/change")
    public String change() {
        return "customer/mobile-change";
    }

    /**
     * 更换手机号码
     *
     * @param customer 登录用户信息
     * @param mobile   更换的手机号码
     * @param authCode 手机验证码
     * @param request  HttpServletRequest
     * @return 返回绑定结果
     */
    @PostMapping("/change")
    @ResponseBody
    public ResponseMessage change(@LoginUser Customer customer, String mobile, String authCode, HttpServletRequest request) {
        ResponseMessage responseMessage = new ResponseMessage();
        if (!ObjectUtil.isMobile(mobile)) {
            return responseMessage.setMessage("请输入正确的手机号码");
        }
        Customer existCustomer = customerService.findByMobile(mobile);
        if (existCustomer != null) { return responseMessage.setMessage("此号码已被绑定,请更换其他手机号码"); }

        HttpSession session = request.getSession();
        String sessionVerifyCode = (String) session.getAttribute(SessionConstants.VERIFY_CODE);
        Long verifyCodeSendTime = (Long) session.getAttribute(SessionConstants.VERIFY_CODE_SEND_TIME);
        if (verifyCodeSendTime == null) { return responseMessage.setMessage("请先获取验证码"); }
        long currentTimeMillis = System.currentTimeMillis();
        // 失效时间:10分钟
        if (verifyCodeSendTime + 1000L * 60 * 10 < currentTimeMillis) {
            return responseMessage.setMessage("验证码失效，请重新获取验证码");
        }
        if (authCode == null || authCode.isEmpty() || !authCode.equals(sessionVerifyCode)) {
            return responseMessage.setMessage("验证码填写错误，请输入正确的验证码");
        }
        customer.setUsername(mobile);
        customer.setMobile(mobile);
        customerService.update(customer);
        return responseMessage.setSuccess(true);
    }

}
